package com.scrapy.http.get;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import com.scrapy.http.pojo.Author;
import com.scrapy.http.pojo.Joke;
import com.scrapy.until.regex.Regex;
import com.scrapy.until.str.StringUtil;

/**
 * 一个页面上所以的笑话
 * @author wanter
 *
 */
public class HttpHelper {
	/**
	 * 拿到封装的httpClient对象
	 */
	private HttpClient httpClient;
	/**
	 * 笑话的集合
	 */
	private List<Joke> jokeList;
	/**
	 * 正则表达式解析出来的放在的位置
	 */
	private Properties properties;
	/**
	 * 最最重要的构造器
	 * 根据正则匹配出对应的笑话的区域
	 * @param httpClient url封装的对象
	 */
	public HttpHelper(HttpClient httpClient, Properties properties) {
		this.properties = properties;
		this.setHttpClient(httpClient);
		String regex = properties.getProperty("conHtml");
		List<String> list = Regex.getListByStringAndRegex(this.getHttpClient().getHttpBody().getCountxt(), regex);
		this.setJokeList(list);
	}

	/**
	 * 拿到httpClient
	 * @return 返回httpClient对象
	 */
	private HttpClient getHttpClient() {
		return httpClient;
	}
	/**
	 * 设置httpCilent
	 * @param httpClient 设置httpClient对象
	 */
	private void setHttpClient(HttpClient httpClient) {
		this.httpClient = httpClient;
	}




	/**
	 * 讲当前所以的页面上的笑话
	 * 都封装到这个list里边
	 * @param list 设置Joke的信息
	 */
	private void setJokeList(List<String> list) {
		this.jokeList  = new ArrayList<>();
		for (String str : list) {

			Joke joke = this.getJoke(str);
			//TODO
			//joke.setAuthor(this.getAuthorByString(str));
			jokeList.add(joke);
		}
		
	}

	/**
	 *
	 * @param str 根据传入的字段获取创作者
	 * @return 返回创作者的信息
	 */
	private Author getAuthorByString(String str){
		Author author = new Author();
		String regex = this.properties.getProperty("idName");
		String idName = Regex.getIdName(str, regex);
		author.setIdName(idName);
		regex = this.properties.getProperty("headImg")+idName+"(\"/>))";
		String igmurl = Regex.getHeadImage(str, regex);
		author.setHeadImg(igmurl);
		author.setAge(0);
		author.setName("未知,人家注册的时候好像没写");
		author.setSexuality("还没有抓取出性别的新方法");
		return author;
	}

	/**
	 * 根据传过来的笑话和字符串
	 * 因为笑话本身含有作者
	 * @param str 字符串信息
	 * @return 返回去笑话内容
	 */
	private Joke getJoke(String str){
		Joke joke = new Joke();
		String regex = this.properties.getProperty("content");
		joke.setContent(StringUtil.removeBr(Regex.getContent(str, regex)));//把笑话内容放进去
		joke.setDate(new Date());//设置抓取的时间
		//TODO
		//joke.setImage("目前还没有抓笑话中图片的功能");
		return joke;
	}
	
	public List<Joke> getJokeList(){
		return this.jokeList;
	}
	

}
